package com.zhiche.lisa.fleet.utils;

import com.zhiche.lisa.fleet.supports.BaseException;
import net.minidev.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;

public class HttpRequestUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);

    public static String sendHttpPost(String url, Map<String, Object> headerMap, Map<String, Object> paramsMap, int socketTimeout) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        Builder builder = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(socketTimeout);
        httpPost.setConfig(builder.build());
        List<NameValuePair> formParams = new ArrayList<>();
        Set set;
        Iterator iterator;
        String key;
        if (null != paramsMap && !paramsMap.isEmpty()) {
            set = paramsMap.keySet();
            iterator = set.iterator();

            while (iterator.hasNext()) {
                key = (String) iterator.next();
                Object value = paramsMap.get(key);
                formParams.add(new BasicNameValuePair(key, null == value ? null : value.toString()));
            }
        }

        if (null != headerMap && !headerMap.isEmpty()) {
            set = headerMap.keySet();
            iterator = set.iterator();

            while (iterator.hasNext()) {
                key = (String) iterator.next();
                String value = !Objects.equals(headerMap.get(key), (Object) null) && !Objects.equals(headerMap.get(key), "") ? headerMap.get(key).toString() : "";
                httpPost.addHeader(key, value);
            }
        }

        String var22;
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            var22 = assemblyReturnData(httpResponse);
        } catch (Exception var19) {
            logger.error("HttpRequestUtil error : {}", var19);
            throw new BaseException(var19.getMessage());
        } finally {
            try {
                httpClient.close();
            } catch (IOException var18) {
                var18.printStackTrace();
            }

        }

        return var22;
    }


    public static String sendHttpPostApplicationJSON(String url,
                                                     Integer socketTimeOut,
                                                     Map<String, Object> param,
                                                     Map<String, Object> header) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig config = RequestConfig.custom().setConnectTimeout(socketTimeOut).setSocketTimeout(socketTimeOut).build();
        httpPost.setConfig(config);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        if (header != null && !header.isEmpty()) {
            for (Map.Entry<String, Object> entry : header.entrySet()) {
                httpPost.setHeader(entry.getKey(), null == entry.getValue() ? null : entry.getValue().toString());
            }
        }
        StringEntity entity = new StringEntity(JSONObject.toJSONString(param));
        entity.setContentType("text/json");
        httpPost.setEntity(entity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        return assemblyReturnData(response);
    }

    private static String assemblyReturnData(CloseableHttpResponse httpResponse) {
        StatusLine statusLine = httpResponse.getStatusLine();
        if (200 == statusLine.getStatusCode()) {
            String var4;
            try {
                HttpEntity entity = httpResponse.getEntity();
                String resultData = entity != null ? EntityUtils.toString(entity) : null;
                if (StringUtils.isBlank(resultData)) {
                    logger.info("assemblyReturnData is null");
                    throw new BaseException("无返回信息");
                }

                var4 = resultData;
            } catch (IOException var14) {
                logger.error("assemblyReturnData error : {}", var14);
                var14.printStackTrace();
                return null;
            } finally {
                try {
                    httpResponse.close();
                } catch (IOException var13) {
                    logger.error("assemblyReturnData error : {}", var13);
                    var13.printStackTrace();
                }

            }

            return var4;
        } else {
            return null;
        }
    }

}
